package com.beyondsoft.common.activiti.support;

import com.beyondsoft.common.activiti.exception.ActivitiException;
import com.beyondsoft.common.activiti.exception.ResultCode;
import com.beyondsoft.common.activiti.model.DiagramResource;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author zhangyan
 * @version $ Id: CustomDeploySupport.java, v 0.1 2020/6/20 11:46 zhangyan Exp $
 */
@Component
@Slf4j
public class CustomDeploySupport {

    @javax.annotation.Resource
    private ProcessEngine processEngine;

    /**
     * 部署流程
     *
     * @param resources
     */
    public void customDeploy(List<DiagramResource> resources) {
        if (!CollectionUtils.isEmpty(resources)) {
            resources.forEach((res) -> {
                this.customDeploy(res.getName(), res.getBpmnFilePath(), res.getImgFilePath());
            });
        }
    }

    /**
     * 部署流程
     *
     * @param name
     * @param bpmnResourceName
     * @param imgResourceName
     * @return
     */
    public String customDeploy(String name, String bpmnResourceName, String imgResourceName) {
        if (StringUtils.isBlank(bpmnResourceName)) {
            throw new ActivitiException(ResultCode.ACCOUNT_PASSWORD_ERROR.getCode(), "发布服务失败，流程文件不存在");
        }
        if (StringUtils.isBlank(name)) {
            name = bpmnResourceName.substring(bpmnResourceName.lastIndexOf("/") + 1, bpmnResourceName.lastIndexOf("."));
        }
        DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService().createDeployment();
        Deployment deployment = null;
        if (StringUtils.isBlank(imgResourceName)) {
            deployment = deploymentBuilder.name(name).addClasspathResource(bpmnResourceName).deploy();
        } else {
            deployment = deploymentBuilder.name(name).addClasspathResource(bpmnResourceName).addClasspathResource(imgResourceName).deploy();
        }
        String deploymentId = deployment.getId();

        return deploymentId;
    }
}
